#include "widget.h"
#include "ui_widget.h"
#include <QMetaProperty>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    boy = new Person("卞京");
    boy->setProperty("score", 15);
    boy->setProperty("age", 10);
    boy->setProperty("sex", "Boy");
    connect(boy, &Person::ageChanged, this, &Widget::on_ageChanged);

    girl = new Person("丁嫣云");
    girl->setProperty("score", 15);
    girl->setProperty("age", 18);
    girl->setProperty("sex", "Girl");
    connect(girl, &Person::ageChanged, this, &Widget::on_ageChanged);

    ui->spinBoy->setProperty("isBoy", true);
    ui->spinGirl->setProperty("isBoy", false);

    void (QSpinBox:: *valueChangedBoySignal)(int) = &QSpinBox::valueChanged;
    void (QSpinBox:: *valueChangedGirlSignal)(int) = &QSpinBox::valueChanged;

    connect(ui->spinBoy, valueChangedBoySignal, this, &Widget::on_spin_valueChanged);
    connect(ui->spinGirl, valueChangedGirlSignal, this, &Widget::on_spin_valueChanged);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_ageChanged(int arg) {
    Q_UNUSED(arg)
    Person *person = qobject_cast<Person*> (sender());
    QString name = person->property("name").toString();
    QString sex = person->property("sex").toString();
    int age = person->getAge();
    ui->textEdit->appendPlainText(name + "," + sex
                                  + QString::asprintf(", 年龄=%d", age));
}

void Widget::on_spin_valueChanged(int arg1) {
    Q_UNUSED(arg1)
    QSpinBox *spinBox = qobject_cast<QSpinBox*> (sender());
    if (spinBox->property("isBoy").toBool())
        boy->setAge(spinBox->value());
    else
        girl->setAge(spinBox->value());
}

void Widget::on_btnClear_clicked()
{
    ui->textEdit->clear();
}

void Widget::on_btnBoyInc_clicked()
{
    boy->incAge();
}

void Widget::on_btnGirlInc_clicked()
{
    girl->incAge();
}

void Widget::on_btnClassInfo_clicked()
{
    const QMetaObject *meta = boy->metaObject();
    ui->textEdit->clear();
    ui->textEdit->appendPlainText("==元对象信息==\n");
    ui->textEdit->appendPlainText(
                QString("类名称：%1\n").arg(meta->className()));
    ui->textEdit->appendPlainText("property");
    for (int i = meta->propertyOffset(); i < meta->propertyCount(); i++) {
        QMetaProperty prop = meta->property(i);
        const char *propName = prop.name();
        QString propValue = boy->property(propName).toString();
        ui->textEdit->appendPlainText(
                    QString("属性名称 = %1, 属性值 = %2").arg(propName).arg(propValue));
    }
    ui->textEdit->appendPlainText("");
    ui->textEdit->appendPlainText("classInfo");
    for (int i = meta->classInfoOffset(); i < meta->classInfoCount(); ++i) {
        QMetaClassInfo classInfo = meta->classInfo(i);
        ui->textEdit->appendPlainText(QString("Name = %1; Value = %2")
                                      .arg(classInfo.name())
                                      .arg(classInfo.value()));
    }
}

